package ldap;

import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.Hashtable;

import static java.lang.System.*;

/**
 * @ClassName LdapLink
 * @Description ldap链接
 * @Author dzf
 * @Date 2022/11/29 8:43
 * @Version 1.0
 */
public class LdapLink {

    //
    private static String linkMode = "ldaps";
    //ldap链接地址
    private static String url = "192.168.81.13";
    //端口（389:不加密、STL 636:SSL）
    private static String port = "636";
    //域名
    private static String domainName = "BEAUAT";
    //LDAP访问安全级别(none,simple,strong)
    private static final String authentication = "simple";
    //访问协议(空、SSL\STL)
    private static final String protocol = "stl";

    public static void main(String[] args) {
        out.println("================LDAP认证开始====================");
        setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification","true");
        String state = "false";
        LdapContext ctxTDS = null;
        try {
            ctxTDS = ldapLink();
        } catch (AuthenticationException e) {
            String extendError = e.toString();

            out.println("extendError===="+extendError);
            String error = "";
            if (extendError.contains("data 525")){
                error = "用户不存在!";
            } else if (extendError.contains("data 52e")) {
                error = "密码或凭证无效!";
            } else if (extendError.contains("data 530")) {
                error = "此时不允许登录!";
            } else if (extendError.contains("data 531")) {
                error = "在此工作站上不允许登录!";
            } else if (extendError.contains("data 532")) {
                error = "密码过期!";
            } else if (extendError.contains("data 533")) {
                error = "账户禁用!";
            } else if (extendError.contains("data 701")) {
                error = "账户过期!";
            } else if (extendError.contains("data 773")) {
                error = "用户必须重置密码!";
            } else if (extendError.contains("data 775")) {
                error = "用户账户锁定!";
            } else {
                error = "账号或密码错误!";
            }
            out.println(error);
        } catch (OperationNotSupportedException e2) {
            out.println("密码不能满足密码策略的要求!");
        } catch (Exception e2) {
            e2.printStackTrace();
            out.println(e2.toString());
            out.println("链接LDAP异常,请联系管理员!");
        } finally {
            if (null != ctxTDS) {
                try {
                    ctxTDS.close();
                } catch (NamingException e) {
                    throw new RuntimeException(e);
                }
                state = "true";//获取对象不为空则登录成功
            }
        }
        out.println(state);
    }

    public static LdapContext ldapLink() throws NamingException {
        String ldapFactory = "com.sun.jndi.ldap.LdapCtxFactory";
//        String ldapAccount = domainName + "\\" + "LCHCCRMTEST01";//用户名
//        String ldapAccount = "uid=dzf,ou=People,dc=dzf,dc=com";
        String ldapAccount = "cn=test,ou=People,dc=dzf,dc=com";
        String ldapWed = "123456";//密码，明文

//        String URL = linkMode + "://" + url + ":" + port;
        String URL = "ldap://192.168.81.13:389";


        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, ldapFactory);
        env.put(Context.PROVIDER_URL, URL);
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
        env.put(Context.SECURITY_CREDENTIALS, ldapWed);
        env.put(Context.SECURITY_PRINCIPAL, ldapAccount);
        env.put(Context.SECURITY_PROTOCOL, protocol);//不传默认不加密
        env.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
        env.put("java.naming.referral", "follow");
        out.println("===================请求报文==============" +env);
        return new InitialLdapContext(env, null);
    }


    public boolean authenticate(String userName, String password) {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "person")).and(
                new EqualsFilter("sAMAccountName", userName));
        return new LdapTemplate().authenticate(String.valueOf(DistinguishedName.EMPTY_PATH), filter
                .toString(), password);
    }

}

